<template>
  <div class="common-layout">
    <!-- 新增人员对话框 -->
    <el-dialog v-model="adddialogVisible" title="新增人员" width="50%" :before-close="handleClose">
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 删除人员对话框 -->
    <el-dialog v-model="deleteDialogVisible" title="删除人员" width="50%" :before-close="handleClose">
      <p>确定要删除用户 <strong>{{ deleteUserName }}</strong> 吗？</p>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmDelete">确认删除</el-button>
        </span>
      </template>
    </el-dialog>
    <el-container>
      <el-header>
        <div class="button-group-container">
          <div class="left-buttons">
            <el-button type="success" @click="openDialog">新增用户</el-button>
            <el-button type="warning" @click="openEditDialog" :disabled="!selectedRow">修改用户</el-button>
            <el-button type="danger" @click="openDeleteDialog" :disabled="!selectedRow">删除用户</el-button>
          </div>
          <div class="right-buttons">
            <el-input
              v-model="searchQuery"
              placeholder="请输入用户姓名或APP名称"
              style="width: 200px; margin-right: 10px"
              clearable
              @clear="handleSearchClear"
              @keyup.enter="handleSearch"
            />
            <el-button type="primary" :icon="Search" @click="handleSearch" />
          </div>
        </div>
      </el-header>
      <el-main style="padding: 0; margin: 0;">
        <el-table 
          :data="tableData" 
          style="width: 100%"
          v-loading="loading"
          @row-click="handleRowClick"
          highlight-current-row
          ref="tableRef"
        >
           <el-table-column width="50"/>
          <el-table-column prop="userName" label="用户姓名" width="200" />
          <el-table-column prop="userInformation" label="用户信息" width="200"/>
          <el-table-column prop="appName" label="APP" width="200" />
          <el-table-column prop="updateTime" label="APP修改时间" width="345">
            <template #default="{row}">
              {{ formatDate(row.updateTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="280" align="center">
            <template #default="scope">
              <div style="display: flex; justify-content: center; gap: 8px;">
                <el-button 
                  type="primary" 
                  size="small" 
                  plain
                  @click.stop="handleGetQRCode(scope.row)"
                  style="min-width: 80px;">
                  <i class="el-icon-picture"></i> 下载
                </el-button>
                <el-button 
                  type="danger" 
                  size="small" 
                  plain
                  @click.stop="handleDeleteApp(scope.row.id)"
                  style="min-width: 80px;">
                  <i class="el-icon-delete"></i> 删除APP
                </el-button>
                <el-button 
                  type="warning" 
                  size="small" 
                  plain
                  @click.stop="handleEditApp(scope.row)"
                  style="min-width: 80px;">
                  <i class="el-icon-edit"></i> 修改APP
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页控件 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'; // 添加这行导入
import { getUserApps,deleteUserApp} from '@/api/userApp' // 假设有这个API接口

// 表格数据
const tableData = ref([])
const loading = ref(false)
const searchQuery = ref('')
const selectedRow = ref(null)
const dialogVisible = ref(false)
const tableRef = ref(null)
const deleteUserName = ref('');

// 弹窗显示状态
const adddialogVisible = ref(false);
const editDialogVisible = ref(false);
const deleteDialogVisible = ref(false);
// 分页参数
const pagination = ref({
  page: 1,
  pageSize: 10,
  total: 0
})

// 排序参数
const sortParams = ref({
  sortBy: 'userName',
  sortDirection: 'asc'
})

// 初始化加载数据
onMounted(() => {
  fetchData()
})

// 打开新增弹窗
const openDialog = () => {
  adddialogVisible.value = true;
}

// 获取数据
const fetchData = async () => {
  try {
    loading.value = true
    const params = {
      page: pagination.value.page,
      pageSize: pagination.value.pageSize,
      sortBy: sortParams.value.sortBy,
      sortDirection: sortParams.value.sortDirection,
      search: searchQuery.value
    }
    
    const response = await getUserApps(params)
    tableData.value = response.data.items
    pagination.value.total = response.data.total
    
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 分页大小变化
const handleSizeChange = (val) => {
  pagination.value.pageSize = val
  fetchData()
}

// 当前页变化
const handleCurrentChange = (val) => {
  pagination.value.page = val
  fetchData()
}

// 搜索
const handleSearch = () => {
  pagination.value.page = 1 // 搜索时重置到第一页
  fetchData()
}

// 清空搜索
const handleSearchClear = () => {
  searchQuery.value = ''
  fetchData()
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString()
}

// 生成二维码
const handleGetQRCode = (row) => {
  // 这里实现二维码生成逻辑
  console.log('生成二维码:', row)
  // window.open(`https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=${row.appUrl}`)
}

// 行点击事件
const handleRowClick = (row) => {
  selectedRow.value = row
  // 设置当前行高亮
  tableRef.value.setCurrentRow(row)
}

// 打开删除对话框
const openDeleteDialog = () => {
  if (!selectedRow.value) {
    ElMessage.warning('请先选择一条记录')
    return
  }
   deleteDialogVisible.value = true;
    deleteUserName.value = selectedRow.value.userName;
}

// 确认删除
const confirmDelete = async () => {
  try {
    if (!selectedRow.value) {
      ElMessage.warning('请先选择一条记录');
      return;
    }

    loading.value = true; // 显示加载状态
    
    // 使用统一的API服务进行删除
    const response = await deleteUserApp(selectedRow.value.userName);
    
    // 根据API服务的统一响应结构处理结果
    if (response.success) {
      ElMessage.success(response.message || '删除成功');
      deleteDialogVisible.value = false;
      fetchData(); // 刷新列表
      
      // 清除当前选中行
      selectedRow.value = null;
      if (tableRef.value) {
        tableRef.value.setCurrentRow(null);
      }
    } else {
      // 如果API调用成功但业务逻辑失败
      throw new Error(response.message || '删除失败');
    }
  } catch (err) {
    console.error('删除操作失败:', err);
    
    // 错误信息处理
    let errorMessage = '删除失败';
    if (err.message) {
      errorMessage = err.message;
    }
    
    // 显示错误提示
    ElMessage.error(errorMessage);
  } finally {
    loading.value = false;
    deleteDialogVisible.value = false;
  }
}

// 打开编辑对话框
const openEditDialog = () => {
  if (!selectedRow.value) {
    ElMessage.warning('请先选择一条记录')
    return
  }
  
  // 这里可以打开编辑对话框
}
</script>

<style scoped>
.common-layout {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.el-header {
  background-color: #fff;
  border-bottom: 1px solid #eee;
  padding: 0 20px;
  height: auto;
  padding: 10px 20px;
}

.button-group-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
}

.left-buttons {
  display: flex;
  gap: 10px;
}

.right-buttons {
  display: flex;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.el-main {
  padding: 20px;
  background-color: #f5f7fa;
}

.el-table {
  margin-top: 10px;
}

/* 当前行高亮样式 */
.el-table__body tr.current-row>td {
  background-color: #f0f7ff !important;
}
</style>  